<template>
  <upload-excel :on-success="handleSuccess" :before-upload="beforeUpload" />
</template>

<script>
import { formatExcelDate } from '@/utils/index'
import { importEmployee } from '@/api/employees'
export default {
  name: 'Import',
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    async handleSuccess({ results, header }) {
      try {
        console.log(results, header)
        // results :[{入职日期:44502,姓名:xxx}]
        // 目标:
        // results:[{timeOfEntry:44502,username:xxx}]
        const arr = this.transExcelHander(results)
        console.log('需要的数组样式', arr)
        const res = await importEmployee(arr)
        console.log(res)
        this.$router.back()
        this.$message.success('操作成功')
      } catch (error) {
        this.$message.error(error.message)
      }
    },

    transExcelHander(results) {
      const userRelations = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber'
      }
      return results.map(item => {
        const obj = {}
        // 样式 ["入职日期","手机号","姓名"]
        Object.keys(item).forEach(key => {
          const enKey = userRelations[key]
          // 判断日期
          if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
            // 要特殊计算
            obj[enKey] = new Date(formatExcelDate(item[key]))
          } else {
            obj[enKey] = item[key]
          }
        })
        return obj
      })
    }
  }
}
</script>
